// ==UserScript==
// @name         zqjs
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  音乐播放器
// @icon         https://hoppinzq.com/zui/static/favicon/favicon.ico
// @author       hoppinzq
// @include      https://*
// @include      http://*
// @include      file://*
// @match        .*
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_addValueChangeListener
// @grant        GM_addStyle
// @grant        GM_getResourceText
// @run-at       document-body
// @resource icon http://150.158.28.40:8804/static/css/font-awesome.css
// @resource css https://hoppinzq.com/hoppin/static/css/zq.css

// @require      https://hoppinzq.com/static/js/vendor/jquery-3.5.1.min.js
// @require      https://hoppinzq.com/static/js/plugins/localforage.js

// ==/UserScript==
var music_list = [
    {
        "id": "-2",
        "name": "时间刺客艾克",
        "singer": "英雄联盟",
        "duration": "03:05",
        "src": "http://hoppinzq.com/hoppin/static/audio/ekko.mp3",
        "type":"default"
    }
]
var player = document.querySelector("#player");
var bz_music = document.querySelector("#bz_music");
var left_photo = document.querySelector("#left_photo");
var list_title = document.querySelector("#list_title");
var list_singer = document.querySelector("#list_singer");
var process_slide = document.querySelector("#process_slide");
var process = document.querySelector("#process");
var showHide = document.querySelector("#showHide");
var time = document.querySelector("#time");
var btnPlay = document.querySelector("#btnPlay");
var volume_slide = document.querySelector("#volume_slide");
var volume = document.querySelector("#volume");
var play_list = document.querySelector("#play_list");
var play_list_area = document.querySelector("#play_list_area");
var music_heart=document.querySelector(".music-heart");
//播放序号
var play_index = 0;

//初始化显示播放列表
//当flag为1的时候,表示列表显示(当前状态)
//当flag为0的时候,表示列表隐藏(当前状态)
var flag = 0;
$(function () {
    $.fn.append2 = function(html, callback) {
        console.log("zq插件 加载成功!");
        let originalHtmlLength = $("body").html().length;
        this.append(html);
        let nums = 1;
        let timer1 = setInterval(function() {
            nums++;
            let clearIntervalfun = function() {
                clearInterval(timer1)
                callback();
            }
            let flag = originalHtmlLength != $("body").html().length || nums > 1000;
            flag && clearIntervalfun()
        }, 1)
    };

    // $("#main_search").keydown(function (e) {2023/11/18 19:00  20:00
    //     if (e.keyCode == 13) {
    //         $(".search-btn").click();
    //         e.preventDefault();
    //     }
    // })

    $("body").append2(`<div id="page_zq_music">音乐</div>`,function () {
        $("#page_zq_music").on("click",function () {
            $("body").toggleClass("nav_music-active");
        })
    });
    initCss();
    $("body").append2(`<div class="nav_music">
    <div class="nav_music__content">
        <div id="bz_music" class="bz_music nav_music__list-item">
            <audio id="player"></audio>
            <div class="music_info">
                <!--                    <div class="left_photo">-->
                <!--                        <a href="javascript:;">-->
                <!--                            <img id="left_photo" src="img/qinaide.jpg" alt="" />-->
                <!--                        </a>-->
                <!--                    </div>-->
                <div class="center_list">
                    <ul>
                        <li class="list_current">
                            <p><span id="list_title" class="list_title"></span>
                                <!--<marquee class="first" scrollamount="2" onclick="this.stop()" onmouseover="this.stop()" onmouseout="this.start()"></marquee>-->
                            </p>
                            <p>
                                <span id="list_singer" class="list_singer"></span>
                            </p>
                        </li>
                    </ul>
                    <div class="search_music_div">
                        <input type="text" class="form-control search_music_input" placeholder="输入歌曲名称 ... ">
                        <button class="btn-search btn-success search_music" type="button">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>
                </div>
                <div class="right_btn">
                    <p style="cursor:pointer;" id="music-icon">
                        <span class="fa fa-angle-double-left"></span>
                    </p>
                    <p id="btn_list">
                        <span id="showHide" class="list fa fa-list"></span>
                    </p>
                    <p style="cursor:pointer;" id="btn_like">
                        <span class="heart fa fa-heart music-heart" style="color: #fff1e5"></span>
                    </p>
                </div>
                <div id="process" class="process">
                    <span id="process_slide" class="process_slide"></span>
                </div>
            </div>
            <!-- ====== 音乐控件 ======= -->
            <div class="music_controls">
                <div id="time" class="time">00:00</div>
                <div class="play_controls">
                    <a id="btnBackward" href="javascript:;" class="btn_back fa fa-backward" onClick="backword()"></a>
                    <a id="btnPlay" href="javascript:;" class="btn_play fa fa-play"></a>
                    <a id="btnForward" href="javascript:;" class="btn_forward fa fa-forward" onClick="forward()"></a>
                </div>
                <div id="volume" class="volume">
                    <span id="volume_slide" class="btn_slide"></span>
                </div>
            </div>
            <!-- ====== 音乐控件end ======= -->
            <!-- ====== 音乐列表 ======= -->
            <div id="play_list_area" class="play_list_area">
                <ul id="play_list" class="play_list">
                </ul>
            </div>
            <!-- ====== 音乐列表end ======= -->
        </div>
    </div>
</div>`,function () {
        player = document.querySelector("#player");
        bz_music = document.querySelector("#bz_music");
        left_photo = document.querySelector("#left_photo");
        list_title = document.querySelector("#list_title");
        list_singer = document.querySelector("#list_singer");
        process_slide = document.querySelector("#process_slide");
        process = document.querySelector("#process");
        showHide = document.querySelector("#showHide");
        time = document.querySelector("#time");
        btnPlay = document.querySelector("#btnPlay");
        volume_slide = document.querySelector("#volume_slide");
        volume = document.querySelector("#volume");
        play_list = document.querySelector("#play_list");
        play_list_area = document.querySelector("#play_list_area");
        music_heart=document.querySelector(".music-heart");
        //初始音量
        player.volume = 0.5;
        //播放列表初始是关闭的
        play_list_area.style.display = "none";
        initMusic();
        $("#music-icon").on("click",function () {
            $('#page_zq_music').click();
        })
        $("#btn_list").on("click",function () {
            showMusicList()
        })
        $("#btn_like").on("click",function () {
            likeMusic()
        })
    });

    // let script = document.createElement("script");
    // script.src = "https://hoppinzq.com/hoppin/static/js/music.js";
    // document.head.appendChild(script);
})

function initCss(){
    let thisCss = [];
    thisCss.push('div#page_zq_music{position: fixed;left: 10px;bottom: 50px;width: 100px;height: 100px;border: 2px solid #000000;zoom:1;filter:alpha(opacity=75);z-index:100 !important;transition:all .3s}');
    let thisStyle = document.createElement('style');
    thisStyle.innerHTML = thisCss.join('\n'),
        document.getElementsByTagName('head')[0].appendChild(thisStyle);

    let icon = GM_getResourceText("icon");
    GM_addStyle(icon);
    let css = GM_getResourceText("css");
    GM_addStyle(css);
}

function initMusic(){
//播放,暂停音乐
    btnPlay.addEventListener("click", function () {
        //paused,表示当前音乐是否为暂停状态
        if (player.paused) {
            //play(),播放当前音乐
            playMusic();
        } else {
            //pause(),暂停当前音乐
            player.pause();
            btnPlay.setAttribute("class", "btn_play fa fa-play");
        }
    })



//音乐结束自动下一首
    player.addEventListener('ended', function () {
        forward();
    }, false);

//设置定时器
    window.setInterval(function () {
        //currentTime,当前播放的秒数
        time.innerHTML = formateTime(player.currentTime);
        //duration,当前音乐的总时长,秒数
        let percent = player.currentTime / player.duration;
        process_slide.style.width = percent * 100 + "%";
    }, 100)


//通过滑块控制音量大小
    volume.addEventListener("click", function (event) {
        //得到当前点击的位置
        let currentVolume = event.offsetX / this.offsetWidth;
        //设置音量
        player.volume = currentVolume;
        window.localStorage.setItem("zq__main_web:volume:music",currentVolume);
        volume_slide.style.width = currentVolume * 100 + "%";
    })

//通过滑块控制音乐进度
    process.addEventListener("click", function (event) {
        //计算点击位置的百分比
        let currentValue = event.offsetX / this.offsetWidth;
        //因为我们已经设置了定时器,在实时监控我们当前音乐的变化
        //因此,我们通过设置当前播放的音乐时长,影响我们的进度条
        player.currentTime = player.duration * currentValue;
    })

//初始化
    firstInit();
    //搜索歌曲
    $(".search_music").click(function () {
        let search_song_name = $(".search_music_input").val();
        if (!search_song_name.trim().length){
            search_song_name = "爱的供养";
            $(".search_music_input").val(search_song_name)
        }else{
            window.localStorage.setItem("zq__main_web:search:music:name",search_song_name);
        }

        $.ajax({
            url: 'http://hoppin.cn:3000/search?keywords=' + search_song_name,
            success: function (data) {
                let songs = data.result.songs;
                music_list=[];
                $.each(songs, function (index, value) {
                    let artist = "";
                    $.each(value.artists, function (index, value) {
                        artist += value.name + " ";
                    })
                    music_list.push({
                        id: value.id,
                        name: value.name,
                        singer: artist,
                        type:"search",
                        duration: timeduration(value.duration),
                        src: "http://music.163.com/song/media/outer/url?id=" + value.id +
                            ".mp3",
                    })
                });
                loadPlayList(music_list);
                flag=0;
                showMusicList();
            }
        })

    })

}

//喜欢音乐
function likeMusic(){
    let song=music_list[play_index];
    if(song.type=="default"){
        alert("默认歌曲不允许操作")
    }else{
        //验证音乐是否被喜欢,喜欢的取消喜欢,未喜欢的喜欢
        //document.querySelector('div').getAttribute('data-user-id');
        if(music_heart.getAttribute('data-store')=="1"){
            //移除indexDB关于歌曲的内容
            localforage.removeItem("zq__music:"+song.id).then(function() {
                alert("取消喜欢成功");
                music_heart.setAttribute()
                $(".music-heart").css("color","#fff1e5").data("store","0");
            }).catch(function(err) {
                alert("取消喜欢失败");
            });
        }else{
            //添加喜欢的歌曲详情
            localforage.setItem("zq__music:"+song.id, song);
            $(".music-heart").css("color","#ad1313").data("store","1");
            alert("喜欢成功");
        }
    }
}
//动态加载播放列表
function loadPlayList(list) {
    $("#play_list").html("");
    //遍历播放列表
    for (let i = 0; i < list.length; i++) {
        //将每个对象，分别存到music中
        let music = list[i];
        //创建li标签
        let liTag = document.createElement("li");
        let divtag=document.createElement("div");
        //创建歌曲名span标签
        let spanTitleTag = document.createElement("p");
        //创建时长span标签
        let spanDurationTag = document.createElement("span");

        //为ul添加li标签，子节点
        play_list.appendChild(liTag);
        liTag.appendChild(divtag);
        //为li标签，添加子节点
        divtag.appendChild(spanTitleTag);
        divtag.appendChild(spanDurationTag);

        //添加内容
        spanTitleTag.innerHTML = music.name;
        spanDurationTag.innerHTML = music.duration;

        //添加类名
        spanTitleTag.classList.add("list_title");
        spanDurationTag.classList.add("list_time");

        //自定义属性
        //需要用的时候，直接从标签中取值，不需要和后台交互
        liTag.setAttribute("data-index", i);
        liTag.setAttribute("data-type", music.type);
        //当点击每一个li标签的时候
        //重新载入歌曲信息(专辑图片、歌曲路径、歌曲名、歌手名)
        //播放当前点击的音乐
        liTag.addEventListener("click", function () {
            //获取每个li标签的歌曲id
            let index = this.getAttribute("data-index");
            //将歌曲id赋给，全局变量play_index
            play_index = index;
            //调用载入歌曲函数
            loadMusic();
            //播放音乐
            playMusic();

            $(this).addClass("active_music_list").siblings().removeClass("active_music_list");
        })
    }
}

//载入歌曲信息
function loadMusic() {
    let music = music_list[play_index];
    //改变专辑图片
    //left_photo.src = music.images;
    //改变歌曲名
    list_title.innerHTML = music.name;
    //改变歌手名
    list_singer.innerHTML = music.singer;
    //改变歌曲路径
    player.src = music.src;
    localforage.getItem("zq__music:"+music.id, function(err, value) {
        if (value != null) {
            $(".music-heart").css("color","#ad1313").data("store","1");
        }else{
            $(".music-heart").css("color","#fff1e5").data("store","0");
        }
    });
}
function timeduration(duration) {
    let st = parseInt(duration / 1000);
    let m = parseInt(st / 60);
    let s = st % 60;
    return "" + addZero(m) + ":" + addZero(s);
}

function addZero(num){
    if (parseInt(num) < 10) {
        num = '0' + num;
    }
    return num;
}
//初始化
function firstInit() {
    let firstSong = music_list[0];
    $("#player").attr("src", firstSong.src);
    $("#list_title").text(firstSong.name);
    $("#list_singer").text(firstSong.singer);

    let search_song_name=window.localStorage.getItem("zq__main_web:search:music:name");
    $(".search_music_input").val(search_song_name);
    let volume=window.localStorage.getItem("zq__main_web:volume:music");
    if(volume==null){
        volume=player.volume;
    }else{
        player.volume=volume
    }

    volume_slide.style.width =  volume * 100 + "%";
    //迭代喜欢的歌曲
    localforage.iterate(function(value, key, iterationNumber) {
        if(key.indexOf("zq__music")!=-1){
            music_list.push(value)
        }
    }).then(function() {
        loadPlayList(music_list);
    }).catch(function(err) {
        loadPlayList(music_list);
    });

    //回车搜索
    $(".search_music_input").keydown(function (e) {
        if (e.keyCode == 13) {
            $(".search_music").click();
            e.preventDefault();
        }
    })
}
//显示隐藏播放列表
function showMusicList() {
    //当前已经显示播放列表
    if (flag) {
        play_list_area.style.display = "none";
        bz_music.style.width = "300px";
        showHide.style.color = "#666";
        flag = 0;
    } else {
        play_list_area.style.display = "block";
        bz_music.style.width = "500px";
        showHide.style.color = "#DDD";
        flag = 1;
    }
}
//静音
function volumeOff() {
    //volume,[0,1]
    player.volume = 0;
    window.localStorage.setItem("zq__main_web:volume:music",0);
    volume_slide.style.width = 0;
}

//最大音
function volumeUp() {
    player.volume = 1;
    window.localStorage.setItem("zq__main_web:volume:music",1);
    volume_slide.style.width = "100%";
}
//播放
function playMusic() {
    player.play();
    btnPlay.setAttribute("class", "btn_play fa fa-pause");
}

//时间转换
function formateTime(time) {
    if (time > 3600) {
        let hour = parseInt(time / 3600);
        let minute = parseInt(time % 3600 / 60);
        let second = parseInt(time % 3600);
        hour = hour >= 10 ? hour : "0" + hour;
        minute = minute >= 10 ? minute : "0" + minute;
        second = second >= 10 ? second : "0" + second;
        return hour + ":" + minute + ":" + second;
    } else {
        let minute = parseInt(time / 60);
        let second = parseInt(time % 60);
        minute = minute >= 10 ? minute : "0" + minute;
        second = second >= 10 ? second : "0" + second;
        return minute + ":" + second;
    }
}
//下一曲
function forward() {
    if (play_index == music_list.length - 1) {
        play_index = 0;
    } else {
        //改变播放序号
        play_index++;
    }
    //重新载入
    loadMusic();
    //播放
    playMusic();
    $("#play_list").find("li").each(function (index,element) {
        if($(element).data("index")==play_index){
            $(element).addClass("active_music_list").siblings().removeClass("active_music_list");
            return;
        }
    })
}
//上一曲
function backword() {
    if (play_index == 0) {
        play_index = music_list.length - 1;
    } else {
        //改变播放序号
        play_index--;
    }
    //重新载入
    loadMusic();
    //播放
    playMusic();
    $("#play_list").find("li").each(function (index,element) {
        if($(element).data("index")==play_index){
            $(element).addClass("active_music_list").siblings().removeClass("active_music_list");
            return;
        }
    })
}